<?php

class SiteController extends RestController
{
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'AppCaptcha',
                'backColor' => 0xFFFCCC,
                'foreColor' => 0x0085EC,
                'maxLength' => 4,
                'minLength' => 4,
                'testLimit' => 1,
                'height' => 50,
                'offset' => 6,
                'transparent' => true,
            ),
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    public function filters()
    {
            return array(
                    array('application.components.AccessFilter - login - captcha - error - index - register - password1
                    	- password2 - mbcode - agreement - CheckMobile - getvcode - Gesture - checkToken'),
                    'COutputCache + list',
                    'duration'=>40,
            );
    }
    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error)
        {
            if(YII_DEBUG)
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $error['type'].' '.$error['message'].' '.$error['file'],
                ));
            else
            {
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => '让我休息下，请稍候再戳',
                ));
            }
        }
    }

    /**
     * 登陆
     */
    public function actionLogin()
    {
        $data              = array('success'=>0);
        $model             = new LoginForm;
        $model->username   = $this->_post('username');
        $model->password   = $this->_post('password');
        $model->verifyCode = $this->_post('verifyCode')?$this->_post('verifyCode'):null;
        if(!in_array(MOBILEOS, array('ios','android')))
            $data['msg'] = 'illegal request param';
        elseif($model->validate() )
        {
            if($model->login())
            {
                $info = Yii::app()->user->info;
                Helper::positionRecord('login',$info['userId']);
                $this->setResult(array(
                    'success' => 1,
                    'info'    => array(
                        'userId' => $info['userId'],
                        'token'  => $info['token'],
                        'mobile' => $info['mobile'],
                    ),
                ));
            }
            else
                $data['msg'] = '用户名或者密码错误';
                
        }
        else
        {
            foreach($model->getErrors() as $error)
            {
                $data['msg'] = $error[0];
                break;
            }
        }
        $num = Yii::app()->cache_php->get('Captcha.numErrorLeft'.$model->username);
        if($num===false || $num>0)
            $data['needCaptcha'] = 0;
        else
            $data['needCaptcha'] = 1;
        $this->setResult($data);
    }
    /**
     * 注册
     */
    public function actionRegister()
    {
        $data                   = array('success' => 0);
        $model                  = new User('register');
        $password               = $this->_post('password');
        $mobile                 = $this->_post('mobile');
        $model->mobile          = $mobile;
        $model->password        = $password;
        $model->verifyCode      = $this->_post('verifyCode');
        $model->register_method = $this->_post('register_method');
        if($model->validate())
        {
            if($model->save())
            {
                $identity = new UserIdentity($mobile, $password,false,true);
                $identity->authenticate();
                if ($identity->errorCode == UserIdentity::ERROR_NONE)
                {
                    $duration = 1800; // 30 days
                    Yii::app()->user->login($identity, $duration);
                    $user = Yii::app()->user->getState('info');
                    $data['success'] = 1;
                    $data['info'] = array(
                        'userId' => $user['userId'],
                        'token'  => $user['token'],
                        'mobile' => $user['mobile'],
                    );
                }
                else
                    $data['msg'] = '注册成功，请登陆';
            }
            else
                $data['msg'] = '对不起，系统维护，请稍后再试';
        }
        else
        {
            foreach($model->getErrors() as $error)
            {
                $data['msg'] = $error[0];
                break;
            }
        }
        $this->setResult($data);
    }

    /*
     * @发送手机验证码  验证手机是否注册
    */
    public function actionMbcode()
    {
        $data = array('success' => 0);
        $mobile = $this->_post('mobile');
        if(!User::mobileRegistered($mobile))
            $data['msg'] = '该手机号尚未注册';
        elseif($this->sms_disabled('get_back_pass'.$mobile,20))
            $data['msg'] = '您的手机号请求过于频繁，请明天再试';
        else
        {
            $code = Helper::randCode($mobile,6,'get_back_password');
            $data['msg'] = '发送失败';
            if ($this->SendSms (0, $mobile, array('file'=>'verifycode','params'=>array('code'=>$code)) ))
            {
                $data['success']     = 1;
                $data['mobile_code'] = YII_DEBUG?$code:0;
                if(MOBILEOS === 'android')
                    $data['mobiles'] = Yii::app()->cache_php->get('appSmsMobiles');
            }
        }
        $this->setResult($data);
    }
    /*
     * @todo  找回密码
     */
    public function actionPassword1()
    {
        $model             = new ForgetPassForm;
        $model->mobile     = $this->_post('mobile');
        $model->verifyCode = $this->_post('verifyCode');
        $model->password   = $this->_post('password');
        $data = array('success'=>0);
        if($model->validate())
        {
            $remote = HttpLib::post($this->javaApi['common_password_reset'],array(
                'mobile'   => $model->mobile,
                'password' => $model->password,
            ));
            if($remote!==null || $remote->success)
            {
                Yii::app()->cache2->del('get_back_password'.$model->mobile);
                $data['success'] = 1;
                $data['msg']     = '密码修改成功';
                Yii::app()->cache_php->del('Captcha.numErrorLeft'.$model->mobile);
                Yii::app()->cache_php->del('captcha.'.$model->mobile);
            }
            else
            {
                $data['success'] = 0;
                $data['msg']     = '密码修改失败,请稍后再试';
            }
        }
        else
        {
            foreach($model->getErrors() as $error)
            {
                $data['msg'] = $error[0];
                break;
            }
        }
        $this->setResult($data);
    }
    /**
     * 获取手机验证码
     */
    public function actiongetvcode()
    {
        $data = array('success'=>0,'msg'=>'');
        $mobile = $this->_post('mobile');
        if(!preg_match('/^1[3|4|5|7|8][0-9]{9}$/', $mobile))
            $data['msg'] = '请输入正确的手机号码';
        elseif($this->sms_disabled('sms_day_'.$mobile))//发送次数限制
            $data['msg'] = '您的手机号请求过于频繁，请明天再试';
        else
        {
            $code = Helper::randCode($mobile);
            $data['msg'] = '发送失败';
            if ($this->SendSms (0, $mobile, array('file'=>'verifycode','params'=>array('code'=>$code)) ))
            {
                $data['success'] = 1;
                $data['msg']     = '发送成功';
                $data['code']    = 200;
                $data['mobile_code'] = YII_DEBUG?$code:0;
                if(MOBILEOS === 'android')
                    $data['mobiles'] = Yii::app()->cache_php->get('appSmsMobiles');
            }
        }
        $this->setResult($data);
    }

    /**
     * 手机端意见反馈
     */
    public function actionFeedBack()
    {
        $data = array('success'=>0);
        $advise = $this->_post('advise');
        $source = $this->_post('source');
        if(empty($advise))
            $data['msg'] = '请填写反馈内容';
        elseif(mb_strlen($advise)>300)
            $data['msg'] = '反馈内容不能多于300字符';
        elseif(!in_array($source, array(1,2)))
            $data['msg'] = '来源参数不合法';
        else
        {
            $result = HttpLib::post($this->javaApi['mobile_feedback'],array(
                'user_id' => $this->_post('user_id'),
                'source'  => $source,
                'advise'  => $advise,
            ));
            $data['msg'] = $result->errorMsg;
            if($result->success)
            {
                $data['msg']     = '反馈提交成功,谢谢';
                $data['success'] = 1;
            }
        }
        $this->setResult($data);
    }
   /**
     * 检验手机号是否已经注册
     */
    public function actionCheckMobile()
    {
        $data = array(
            'success' => 0,
            'msg'     => '该手机号尚未注册',
        );
        $mobile = $this->_post('mobile');
        if(!preg_match('/^1[3|4|5|7|8][0-9]{9}$/', $mobile))
        {
            $data['success'] = -1;
            $data['msg']     = '请输入正确的手机号码';
        }
        elseif(User::mobileRegistered($mobile))
        {
            $data['success'] = 1;
            $data['msg']     = '该手机号已经注册';
        }
        $this->setResult($data);
    }
    /**
     * 草根协议页面(注册时展示)
     */
    public function actionagreement()
    {
        $this->render('_agreement');
    }
    /**
     * 手势
     */
    public function actionGesture()
    {
        $data = array('success' => 0);
        $params = array(
            'user_id'  => $this->_post('user_id'),
            'token'    => TOKEN,
        );
        if($this->checkUserToken($params['user_id'],$params['token']))
            $data['success'] = 2;
        else
            $data = $this->actionLogin();
        $this->setResult($data);
    }
    /**
     * 校验token
     */
    public function actionCheckToken()
    {
        $data = array('success' => 0);
        $params = array(
            'user_id'  => $this->_post('user_id'),
            'token'    => TOKEN,
            'password' => $this->_post('password'),
        );
        if(!$this->checkUserToken($params['user_id'],$params['token']))
            $data['success'] = 2;
        elseif(!User::model()->checkPayPass($params['user_id'],$params['password']))
        {
            $data['success'] = 3; 
            $data['msg']     = '交易密码不正确';
        }
        else
            $data['success'] = 1;
        $this->setResult($data);
    }
}
